﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Convertor.Interface;
using System.IO;
using Wpf.CommonTools;
using System.Collections.ObjectModel;
using Wpf.CommonTools.SystemExtension;
using System.Windows;

namespace Convertor
{
    /// <summary>
    /// Plugin handler
    /// </summary>
    class PluginHandler
    {
        /// <summary>
        /// Loading all available plugins from disk
        /// </summary>
        /// <returns></returns>
        public static void LoadPlugs()
        {
            Config.GlobalConfig.AllPlugins.Clear();
            string rootPath = System.AppDomain.CurrentDomain.BaseDirectory;
            string[] files = System.IO.Directory.GetFiles(rootPath, @"*.Plugin.*.dll");
            foreach (string file in files)
            {
                FileInfo fileInfo = new FileInfo(file);
                if (!string.IsNullOrEmpty(fileInfo.Name))
                {
                    System.Reflection.Assembly asm = System.Reflection.Assembly.LoadFrom(fileInfo.FullName);
                    string asmName = System.IO.Path.GetFileNameWithoutExtension(fileInfo.Name);
                    object plugin = null;
                    try
                    {
                        plugin = System.Activator.CreateInstance(asm.GetType(asmName + "." + "Plugin"));
                    }
                    catch
                    {
                    }
                    IPluginInfo iApp = plugin as IPluginInfo;
                    if (iApp != null)
                    {
                        iApp.Order = -1;
                        if (iApp != null)
                        {
                            Config.GlobalConfig.AllPlugins.Add(fileInfo.Name, plugin);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Loading all available templates from disk
        /// </summary>
        public static void LoadAllTemplates()
        {
            Config.GlobalConfig.TemplateList.Clear();

            string[] files = System.IO.Directory.GetFiles(Config.GlobalConfig.WorkspacePath, @"*.cvt1"); //Loading all user saved templates
            foreach (string file in files)
            {
                TemplateToSaveContainer tlt = PluginHandler.LoaTemplateFromSerializeFile(file);
                Config.GlobalConfig.TemplateList.Add(new TemplateToLoadViewModel() { Name = tlt.Name, Description = tlt.Description, Path = tlt.Path, UniqueId = tlt.UniqueId });
            }

            files = System.IO.Directory.GetFiles(Config.SystemTemplatePath, @"*.cvt1"); //Loading all default templates
            foreach (string file in files)
            {
                TemplateToSaveContainer tlt = PluginHandler.LoaTemplateFromSerializeFile(file);
                Config.GlobalConfig.TemplateList.Add(new TemplateToLoadViewModel() { Name = tlt.Name, Description = tlt.Description, Path = tlt.Path, UniqueId = tlt.UniqueId });
            }
        }
        /// <summary>
        /// Loading template from disk by filePath
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static TemplateToSaveContainer LoaTemplateFromSerializeFile(string filePath)
        {
            TemplateToSaveContainer a = null;
            try
            {
                a = Wpf.CommonTools.FileExtension.Processing.LoadFile<TemplateToSaveContainer>(filePath ?? Config.TempPluginsSavePath);
            }
            catch (Exception ex)
            {
                a = new TemplateToSaveContainer() { Name = "____ErrorTemplate", Description = ex.ToString(), Path = filePath };
            }
            a.Path = filePath;
            return a ?? new TemplateToSaveContainer();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="uniqueId"></param>
        /// <returns></returns>
        public static Collection<IPluginItem> GetPluginsFromTemplateByUniqueId(string uniqueId)
        {
            var template = Config.GlobalConfig.TemplateList.FirstOrDefault(p => p.UniqueId == uniqueId);
            if (template != null)
            {
                return LoaTemplateFromSerializeFile(template.Path).Plugins;
            }
            else
            {
                return new Collection<IPluginItem>();
            }
        }
        /// <summary>
        /// Save Template to disk
        /// </summary>
        /// <param name="template"></param>
        /// <param name="pathName"></param>
        public static void SaveTemplateToDisk(TemplateToSaveContainer template, string pathName)
        {
            Wpf.CommonTools.FileExtension.Processing.SaveFile(template, pathName);
        }
        /// <summary>
        /// Save Template to disk
        /// </summary>
        /// <param name="plugins">To save plugin list</param>
        /// <param name="isTemp"></param>
        public static void SavePluginAsTemplateToDisk(IPluginsItemCollection plugins, bool isTemp)
        {

            if (Config.CurrentTemplate.Container.Lock == true)
            {
                if (Config.CurrentTemplate.Container.UserId != Config.GlobalConfig.UserId)
                {
                    MessageBox.Show(UILanguage.FindResource("PluginIsLocked"));
                    return;
                }
            }
            if (plugins == null)
            {
                plugins = new PluginsItemCollection();
            }
            string path = isTemp ? Config.TempPluginsSavePath : Config.CurrentTemplate.Container.Path;
            Config.CurrentTemplate.Container.Plugins = plugins.SelectedPlugins;
            Config.CurrentTemplate.Container.SaveDate = DateTime.Now;
            Config.CurrentTemplate.Container.UserId = Config.GlobalConfig.UserId;
            try
            {
                PluginHandler.SaveTemplateToDisk(Config.CurrentTemplate.Container, path);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
